package com.youku.scope;

import java.util.HashMap;
import java.util.Map;

/**
 * 作用域
 * 
 * @author loda
 *
 */
public class Scope {

	private Map<String, Symbol> members = new HashMap<>();

	private Scope enclosingScope;

	private String scopeName;

	public Scope() {
	}

	public Scope(Scope enclosingScope) {
		this.enclosingScope = enclosingScope;
	}

	public void def(Symbol s) {
		members.put(s.getName(), s);
	}

	public Scope enclosingScope() {
		return enclosingScope;
	}

	public String scopeName() {
		return scopeName;
	}

	/**
	 * 查找变量是否在该作用域中
	 * 
	 * 如果不在，则继续查找外围作用域 如果在，则直接返回变量
	 */
	public Symbol resolve(String name) {
		Symbol symbol = members.get(name);
		if (symbol == null) {
			Scope scope = enclosingScope();
			if (scope != null)
				return scope.resolve(name);
			else
				return null;
		} else {
			return symbol;
		}
	}

}
